<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" @submit.native.prevent>
            <el-form-item label="规格名称" prop="specName">
              <el-input v-model="queryParams.specName" placeholder="请输入商品规格名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <div class="content">
      <div v-show="tableHeight && showTree" :span="edgeSize" :offset="0" :style="`height: ${tableHeight}px;position: relative;background-color:#fff`">
        <div class="left" :style="`height: ${tableHeight}px;`">
          <div class="left-top">
            <div class="">规格分类</div>
            <div class="">
              <img style="width: 30px; height: 30px" @click="handleEdge" :src="showTree ? imgs[1] : imgs[0]" />
            </div>
          </div>
          <el-tree
            ref="classifyTreeRef"
            class="mt-2"
            node-key="id"
            :data="groupList"
            :props="{ label: 'specGroupName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="itemClick"
          />

          <div class="buttons">
            <div class="button" @click="handleAddGroup">
              <el-icon>
                <CirclePlus />
              </el-icon>
              <div>新增分组</div>
            </div>
            <div class="button" @click="editTemplate">
              <el-icon>
                <Edit />
              </el-icon>
              <div>编辑分组</div>
            </div>
            <div class="button" @click="handleDeleteGroup">
              <el-icon>
                <Delete />
              </el-icon>
              <div>删除分组</div>
            </div>
          </div>
        </div>
      </div>

      <el-card shadow="never" ref="table" :class="{ 'w-tree': showTree, 'w-all': !showTree }">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['order:goodsSpec:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['order:goodsSpec:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['order:goodsSpec:remove']"
                >删除</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" icon="Download" @click="handleExport" v-hasPermi="['order:goodsSpec:export']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>

        <el-table v-loading="loading" border :data="goodsSpecList" :height="'calc(100vh - 422px)'" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="规格名称" align="center" prop="specName" />
          <el-table-column label="规格分组" align="center" prop="specGroupName" />
          <!-- <el-table-column label="排序" align="center" prop="sort" /> -->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:goodsSpec:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:goodsSpec:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
    </div>

    <div class="fixed-icon" @click="handleEdge" v-show="!showTree">
      <el-icon>
        <DArrowRight />
      </el-icon>
    </div>
    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="goodsSpecFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规格分组" prop="specGroupId">
          <el-tree-select
            :props="{ value: 'id', label: 'specGroupName', children: 'children' }"
            v-model="form.specGroupId"
            :data="groupList"
            clearable
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="规格名称" prop="specName">
          <el-input v-model="form.specName" placeholder="请输入规格名称" />
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort" placeholder="请输入排序" />
                </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <addGroupFrom ref="addGroupFromRef" @ok="getGroupList" />
  </div>
</template>

<script setup name="GoodsSpec" lang="ts">
import { ref, reactive, toRefs, onMounted, getCurrentInstance, ComponentInternalInstance, nextTick } from 'vue';
import { listGoodsSpec, getGoodsSpec, delGoodsSpec, addGoodsSpec, updateGoodsSpec } from '@/api/goods/goodsSpec';
import { listGoodsSpecGroup, delGoodsSpecGroup } from '@/api/goods/goodsSpecGroup';
import { GoodsSpecVO, GoodsSpecQuery, GoodsSpecForm } from '@/api/goods/goodsSpec/types';
import addGroupFrom from './modules/addGroupFrom.vue';
import zk from '@/assets/images/zhankai.svg';
import zd from '@/assets/images/zhedie.svg';
import { handleTree, findNodeInTree } from '@/utils/ruoyi';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const addGroupFromRef = ref();
const goodsSpecList = ref<GoodsSpecVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const currentIndex = ref(0);
const classifyTreeRef = ref<ElTreeInstance>();
const showTree = ref(true);
interface Tree {
  id: number | string;
  specGroupName: string;
  children?: Tree[];
}
const groupList = ref<Tree[]>([]);
const queryFormRef = ref<ElFormInstance>();
const goodsSpecFormRef = ref<ElFormInstance>();
const groupName = ref('');
const edgeSize = ref(4);
const imgs = [zk, zd];
const tableHeight = ref(0);
const table = ref(null);
const currentRow = ref(null);

const groupTreeRef = ref<ElTreeInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: GoodsSpecForm = {
  id: undefined,
  specName: undefined,
  specGroupId: undefined,
  sort: undefined
};
const data = reactive<PageData<GoodsSpecForm, GoodsSpecQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    specName: undefined,
    specGroupId: undefined,
    sort: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    specName: [{ required: true, message: '商品规格名称不能为空', trigger: 'blur' }],
    specGroupId: [{ required: true, message: '分组id不能为空', trigger: 'change' }],
    sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品规格列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGoodsSpec(queryParams.value);
  goodsSpecList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData, specGroupId: groupList.value[currentIndex.value]?.id };
  goodsSpecFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  classifyTreeRef.value?.setCurrentKey(null);
  currentRow.value = null;
  queryParams.value.specGroupId = null;

  nextTick(() => {
    setTimeout(() => {
      tableHeight.value = table.value.$el.scrollHeight;
    }, 200);
  });
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: GoodsSpecVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加商品规格';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GoodsSpecVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getGoodsSpec(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改商品规格';
};

/** 提交按钮 */
const submitForm = () => {
  goodsSpecFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateGoodsSpec(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGoodsSpec(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
const handleEdge = () => {
  showTree.value = !showTree.value;

  nextTick(() => {
    setTimeout(() => {
      tableHeight.value = table.value.$el.scrollHeight;
    }, 200);
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: GoodsSpecVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商品规格？').finally(() => (loading.value = false));
  await delGoodsSpec(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/goodsSpec/export',
    {
      ...queryParams.value
    },
    `goodsSpec_${new Date().getTime()}.xlsx`
  );
};
// 添加分组
const handleAddGroup = () => {
  const data = currentRow.value ? currentRow.value : { id: 0, specGroupName: '全部' };
  addGroupFromRef.value.add(data);
};
// 编辑分组
const editTemplate = () => {
  if (!currentRow.value) {
    proxy?.$modal.msgError('请选择要编辑的分组');
    return;
  }
  addGroupFromRef.value.edit(currentRow.value);
};
// 删除分组
const handleDeleteGroup = () => {
  if (!currentRow.value) {
    proxy?.$modal.msgError('请选择要删除的分组');
    return;
  }
  proxy?.$modal
    .confirm('是否确认删除商品规格分组？')
    .then(async () => {
      await delGoodsSpecGroup(currentRow.value.id);
      proxy?.$modal.msgSuccess('删除成功');

      loading.value = false;
      currentRow.value = null;
      getGroupList();
    })
    .finally(() => {});
};
// 聚焦

const setCurrentKey = () => {
  nextTick(() => {
    if (findNodeInTree(groupList.value[0], currentRow.value.id)) {
      classifyTreeRef.value.setCurrentKey(currentRow.value.id);
    } else {
      classifyTreeRef.value.setCurrentKey(null);
      itemClick({});
    }
  });
};
// 获取分组列表
const getGroupList = async () => {
  const res = await listGoodsSpecGroup();
  groupList.value = [
    {
      id: 0,
      specGroupName: '全部',
      children: handleTree(res.rows)
    }
  ];
  setCurrentKey();
};

const itemClick = (item) => {
  currentRow.value = item;
  queryParams.value.specGroupId = item.id || null;
  getList();
};
/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  console.log('data :>> ', data);
  if (!value) return true;
  return data.specGroupName.indexOf(value) !== -1;
};
const handleNodeClick = (data) => {
  if (data.id === 0) {
    queryParams.value.specGroupId = undefined;
  } else {
    queryParams.value.specGroupId = data.id;
  }
  getList();
};
onMounted(() => {
  getList();
  getGroupList();
  nextTick(() => {
    setTimeout(() => {
      tableHeight.value = table.value.$el.scrollHeight;
      console.log('tableHeight :>> ', tableHeight);
    }, 200);
  });
});
/** 根据名称筛选部门树 */
watchEffect(
  () => {
    groupTreeRef.value?.filter(groupName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);
</script>
<style scoped lang="scss">
.p-2 {
  overflow-x: hidden;
}

.tree-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /* border-bottom: 1px solid #777; */
  /* padding: 5px 0; */
  cursor: pointer;
  background-color: #fff;
}

.tree-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.item__selected {
  background-color: #e6f7ff;
}

.tree__line {
  width: 24px;
  height: 24px;
  border-bottom: 1px dashed #e5e5eb;
  border-left: 1px dashed #e5e5eb;
}

.tree__title {
  padding: 0 4px;
  margin-bottom: -24px;
}

.left {
  width: 240px;
  height: calc(100vh - 234px);
  border: 1px solid #e6ebf5;
  position: relative;
  border-radius: 4px;
  overflow: hidden;

  .fodder_list {
    z-index: 20;

    .fodder_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 20px;
      cursor: pointer;

      .box {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        svg {
          margin-right: 10px;
        }
      }
    }

    .fodder_item.active,
    .fodder_item:hover {
      background-color: #f5f5f5;
    }
  }

  .buttons {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    position: absolute;
    bottom: 0;
    width: 240px;
    border-top: 1px solid #e6ebf5;
    background-color: #fff;
    z-index: 21;
    font-size: 12px;
    color: #303133;

    .button {
      cursor: pointer;
      padding: 10px;
      text-align: center;

      i {
        margin-right: 5px;
      }
    }

    .button:not(:last-child) {
      border-right: 1px solid #e6ebf5;
    }

    .button:hover {
      color: #409eff;
    }
  }
}

.left-top {
  display: flex;
  justify-content: space-between;
  padding: 6px 20px;
  border-bottom: 1px solid #e6ebf5;
  align-items: center;

  .box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 24px;
    color: #303133;
    font-weight: bold;
  }
}

.fixed-icon {
  position: fixed;
  //left: 0;
  top: 400px;
  z-index: 999;
  background-color: #409eff;
  padding: 12px 2px;
  color: #fff;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  display: flex;
  cursor: pointer;
}

.content {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.w-tree {
  width: calc(100% - 260px);
}

.w-all {
  width: 100%;
}
</style>